<template>
    <div :class="classes">
    	<div :class="classTabsHd">
            <ul :class="classTabsNav">
                <!--标题页的标题 v-for遍历, :class 动态绑定class-->
                <li :class='tabCls(item)' v-for="(item,index) in navList" :key="item.name" @click="handleChange(index)">
                    {{item.label}}
                    <span v-html="item.slot" v-if='item.slot'></span>
                    <span class="mj-tab-close" v-if="item.closable">
                        <Icon type="close" @click.native.stop="close(item, index)"></Icon>
                    </span>
                </li>
            </ul>
            <slot name="extra"></slot>
    	</div>
        <div :class="[prefixCls+'-tabs-content']" ref="panes" :style="animation">
            <!--这里的slot就是嵌套的pane组件的内容-->
            <slot></slot>
        </div>
    </div>
</template>
<script>
import { prefixCls } from '../prefix'

const transitionTime = 300;
export default {
    name: `${prefixCls}Tabs`,
    data: function() {
        return {
            prefixCls: prefixCls,
            //将pane的标题保存到数组中
            navList: [],
            //保存父组件的value到currentValue变量中，以便在本地维护
            currentValue: this.value,
            // 启用动画
            animation:'',
            focusedKey: this.value
        }
    },
    provide () {
        return { TabsInstance: this };
    },
    props: {
        //接收父组件的value
        value: {
            type: [String, Number],
            default:''
        },
        animated: {
            type:Boolean,
            default:false
        },
        tabPosition: {
            type: String,
            default: ''
        }
    },
    computed: {
        classes() {
            return [
                `${prefixCls}-tabs`,
                {
                    'open': this.show,
                    [prefixCls + '-tabs-is-animation']: this.animated,
                    [prefixCls + '-left']: this.tabPosition === 'left'
                }
            ]
        },
        classTabsHd() {
            return [
                {   
                    [prefixCls+'-tabs-hd']: this.tabPosition != 'left',
                    [prefixCls+'-left-tabs-hd']: this.tabPosition === 'left'
                }
            ]
        },
        classTabsNav() {
            return [
                {
                    [prefixCls+'-tabs-nav']:this.tabPosition != 'left',
                    [prefixCls+'-left-tabs-nav']:this.tabPosition === 'left'
                }
            ]
        }
        
    },
    mounted(){
    },
    methods: {
        //使用$children遍历子组件，得到所有的pane组件
        getTabs: function() {
            // console.log(this)
            return this.$children.filter(function(item) {
                return item.$options.name === 'mjTabPane';
            })
        },
        close(item, index) {
            const tabs = this.getTabs();
            const tab = tabs[index];
            tab.$destroy();
            if (tab.name === this.currentValue) {
                const newTabs = this.getTabs();
                let activeKey = -1;
                let translateNumber = 0
                if (newTabs.length) {
                    const leftNoDisabledTabs = tabs.filter((item, itemIndex) => !item.disabled && itemIndex < index);
                    const rightNoDisabledTabs = tabs.filter((item, itemIndex) => !item.disabled && itemIndex > index);
                    if (rightNoDisabledTabs.length) {
                        activeKey = rightNoDisabledTabs[0].name;
                        translateNumber = index
                    } else if (leftNoDisabledTabs.length) {
                        activeKey = leftNoDisabledTabs[leftNoDisabledTabs.length - 1].name;
                        translateNumber = index - 1
                    } else {
                        activeKey = newTabs[0].name;
                        translateNumber = index
                    }
                }
                this.currentValue = activeKey
                this.$emit('input', activeKey);
                if(this.animated) {
                    this.animation = 'transform: translate3d(-' + translateNumber * 100 + '%, 0px, 0px)'
                }
            }
            this.$emit('on-tab-remove', tab.name);
            this.updateNav();
        },
        //更新tabs
        updateNav() {
            this.navList = [];
            var _this = this;
            this.getTabs().forEach(function(pane, index) {
                _this.navList.push({
                    label: pane.label,
                    name: pane.name || index,
                    disabled: pane.disabled,
                    closable: pane.closable,
                    slot:pane.$slots.label?pane.$slots.label[0].elm.innerHTML:"",
                });
                //如果没有设置name，默认设置为索引值
                if(!pane.name) {
                    pane.name = index;
                }
                //设置第一个pane为当前显示的tab
                if(index === 0) {
                    if(!_this.currentValue) {
                        _this.currentValue = pane.name || index;
                    }
                }
                // 隐藏name=label的slot，不在内容中显示
                pane.slotShow = false
            });
            this.updateStatus();
        },
        updateStatus() {
            var _this = this;
            var tabs = _this.getTabs();
            //显示当前选中的tab对应的pane组件，隐藏没有选中的
            tabs.forEach(function(tab) {
                if(_this.animated) {
                    return tab.show = true
                }else{
                    return tab.show = tab.name === _this.currentValue;
                }

            })
        },
        tabCls: function(item) {
            return [
                'mj-tabs-tab',
                {
                    //为当前选中的tab加一个tabs-tab-active class
                    'mj-tabs-tab-active': item.name === this.currentValue && this.tabPosition != 'left',
                    // 是否禁用该选项卡
                    'mj-tabs-tab-disabled': item.disabled,
                    'mj-left-tabs-tab-active': item.name === this.currentValue && this.tabPosition === 'left'
                }
            ]
        },
        //点击tab标题触发
        handleChange: function(index) {
            var nav = this.navList[index];
            var name = nav.name;
            //改变当前选中的tab，触发watch
            this.currentValue = name;
            //实现子组件与父组件通信
            this.$emit('click', name);
            if(this.animated) {
                this.animation = 'transform: translate3d(-' + index * 100 + '%, 0px, 0px)'
            }
        },
        getTabIndex(name){
            return this.navList.findIndex(nav => nav.name === name);
        },
        updateVisibility(index){
            [...this.$refs.panes.querySelectorAll(`.${prefixCls}-tabs-tabpane`)].forEach((el, i) => {
                if (index === i) {
                    [...el.children].filter(child=> child.classList.contains(`${prefixCls}-tabs-tabpane`)).forEach(child => child.style.visibility = 'visible');
                } else {
                    setTimeout(() => {
                        [...el.children].filter(child=> child.classList.contains(`${prefixCls}-tabs-tabpane`)).forEach(child => child.style.visibility = 'hidden');
                    }, transitionTime);
                }
            });
        }
    },
    watch: {
        value(val) {
            this.currentValue = val;
            this.focusedKey = val;
        },
        currentValue(val) {
            //tab发生变化时，更新pane的显示状态
            this.updateStatus();

            //const nextIndex = Math.max(this.getTabIndex(this.focusedKey), 0);
            //this.updateVisibility(nextIndex)
        }
    }
  }
</script>
